<?php
class webSite {
	/*
	 * http://localhost/weixin/call.json?userName=fromuser&customerId=1&module=webSite&method=getWebSite&params={%22id%22:1}
	*/
	public static function getWebSiteById($id, $user, $rootId = NULL){		
		$material = webSite::getMaterial($id);
		if (!$material) {
			return;
		}
        //阅读量递增.
        $websiteModel = m("material");
        $readCount['readCount'] = $material->readCount + 1;
        $websiteModel->where("id = {$id}")->save($readCount);

		$materialObj = simplexml_load_string($material->xml,
				'SimpleXMLElement', LIBXML_NOCDATA);
		if ($materialObj == NULL) {
			return;
		}
		
		$cid = $user['customerId'];
		$userName = $user['userName'];
		
		if(isset($rootId)) {
			$materialObjNav = webSite::getMaterialObj($rootId);
			if ($materialObjNav == NULL) {
				return;
			}
		} else {
			$materialObjNav = $materialObj;
			$rootId = $id;
		}
		
		$mainArticles = array();
		$mainXml = $materialObj->MainArticles;
		if ($mainXml->item) {
			foreach ($mainXml->item as $item) {
				$arrItem = array();
				$arrItem['title'] = $item->title;
				$arrItem['picurl'] = $item->picurl;
				if (strstr($item->url, C('SERVER_HOST'))) {
					$arrItem['url'] = webSite::getTpl(get_session_url($item->url, $cid, $userName), $rootId);
				} else {
					$arrItem['url'] = $item->url;
				}
				array_push($mainArticles, $arrItem);
			}
		}
		$moduleArticles = array();
		$moduleXml = $materialObj->ModuleArticles;
		if ($moduleXml->item) {
			foreach ($moduleXml->item as $item) {
				$arrItem = array();
				$arrItem['title'] = $item->title;
				$arrItem['subtitle'] = $item->subtitle;
				$arrItem['picurl'] = $item->picurl;
				if (strstr($item->url, C('SERVER_HOST'))) {
					$arrItem['url'] = webSite::getTpl(get_session_url($item->url, $cid, $userName), $rootId);
				} else {
					$arrItem['url'] = $item->url;
				}
				$arrItem['color'] = $item->color;
				array_push($moduleArticles, $arrItem);
			}
		}
		
		$randomBackground = "";
		$backgroundArticles = array();
		$backgroundXml = $materialObj->ModuleBackgrounds;
		$bgItem = $backgroundXml->item;
		if ($bgItem) {
			foreach ($backgroundXml->item as $item) {
				$arrItem = array();
				$arrItem['picurl'] = $item->picurl;
				array_push($backgroundArticles, $arrItem);
			}
			
			// use random background
			$bgCount = count($bgItem);
			$random = rand(0, $bgCount - 1);
			$randomBackground = $bgItem[$random]->picurl;
		}

		$result = array();
		$result['shareinfo'] = (string)$materialObj->shareinfo;
		$result['sharepicurl'] = (string)$materialObj->sharepicurl;
		$result['title'] = $material->name;
		$result['MainArticles'] = $mainArticles;
		$result['ModuleArticles'] = $moduleArticles;
		$result['backgrounds'] = $backgroundArticles;
		$result['randomBackground'] = $randomBackground;
		$result['accessTag'] = $material->accessTag;
		//ihziluoh 添加标签
			if(!empty($result['accessTag']) && !empty($userName)){	
				setAccessTags($result['accessTag'],$userName,module_handle_webSite, $id);
			}
			//ihziluoh 添加标签
		if (isset($materialObjNav)) {
			$nav = webSite::getNav($materialObjNav, $cid, $userName, $rootId);
			$result["header"] = $nav["header"];
			$result["footer"] = $nav["footer"];
			$result["headerTpl"] = $nav["headerTpl"];
			$result["footerTpl"] = $nav["footerTpl"];
		}
		
		$templateId = (int)$materialObj->templateid;
		if (!isset($templateId)) {
			$templateId = 1;
		}
		//ds 2014/6/25
		//根据查询到的主题模版ID获取对应的html模版名
		$customerId = Session::$user['customerId'];
		Session::switchCustomer(0);
		$websitetemplate = m('website_template');
		$where['id'] =array('eq',$templateId);
		$templatename = $websitetemplate->field('moduleHtmlName')->where($where)->find();
		Session::switchCustomer($customerId);
		//如果存在对应html模版则使用上面id对应的主题模版
		if(!empty($templatename)){
			$module = $templatename['moduleHtmlName'];
		}else{ //数据库没有此id对应的主题模版时走这里
			switch ($templateId) {
				case 1:
					$module = 'website';
					break;
				case 2:
					$module = 'website_four_module';
					break;
				case 3:
					$module = 'website_color_block';
					break;
				case 4:
					$module = 'website_list';
					break;
				case 5:
					$module = 'website_four_toolbar';
					break;
				case 6:
					$module = 'website_left_right';
					break;
				case 7:
					$module = 'website_list_imgtxt_1';
					break;
				default:
					$module = 'website';
					break;
			}
		}
		Output::instance()->module('webSite', $module)->object($result);
	}
	//根据标签模板id获取详细信息
	public static function getTagTemplateById($tplid){
		$tagModel = M();
		$sql = 'select * from wx_webpage_tag_template where id ='.$tplid;
		$res = $tagModel->query($sql);
		return $res;
	}
	
	// 废弃，请用webpage中的方法替代
	public static function getWebSiteTag($field, $value, $start, $limit,$tplid) {	
		$TagModel = M("web_page_tag");
		$res  = webSite:: getTagTemplateById($tplid);	
		$htmlname =$res[0]['htmlname']==''?'website_tag' :$res[0]['htmlname'];
		if($field == 'tagName'){
			$tag = $TagModel->field("tagName,picUrl,description")->where("$field='$value'")->find();
			$tagName = $value;
		}else if($field == 'id'){
			$tag = $TagModel->field("tagName,picUrl,description")->where("$field='$value'")->find();
			$tagName = $tag["tagName"];
		}
		
		
		$sql = $TagModel->field("id")->where("$field='$value'")->select(false);
		$condition["_string"] = "tagId in ($sql)";
		$TagListModel = M("web_page_tag_list");
		$sql = $TagListModel->field("webPageId")->where($condition)->select(false);
		$where["_string"] = "id IN ($sql)";
		$where["deleted"] = 0;
		$WebPageModel = M("web_page");
		$arr = $WebPageModel->where($where)->order("stickyPostTime desc, updateTime desc")->limit($start, $limit)->select();
		//echo $WebPageModel->getLastSql();
		if ($arr) {
			for($i = 0; $i < count($arr); $i++) {
				if ($arr[$i]["comment"] == "1" || $arr[$i]["rate"] == "1") {
						
					$obj = get_comment_and_rate_obj_by_moduleId($arr[$i]["id"], "webPage");
					if ($obj) {
						// "0" won't show in page
						$arr[$i]["commentCount"] = $obj["commentCount"] == "0" ? " 0" : $obj["commentCount"];
						$arr[$i]["rateCount"] = $obj["rateCount"] == "0"? " 0" : $obj["rateCount"] ;
					} else {
						$arr[$i]["commentCount"] = " 0";
						$arr[$i]["rateCount"] = " 0";
					}
				}
				if($i == 0){
					$arr[$i]["tagName"] = $tagName;
					$arr[$i]["picUrl"] = $tag['picUrl'];
					$arr[$i]["description"] = $tag['description'];
				}
			}
			Output::instance()->module('webSite', $htmlname)->objArray($arr,  $WebPageModel->where($where)->count());
		} else {
			Output::instance()->module('webSite', $htmlname)->resultCode(code_success);
		}
	}
	
	private static function getMaterial($id) {
		$MaterialModel = D("Material");
		
		$map["id"] = $id;
		$material = $MaterialModel->where($map)->find();
		if (!$material) {
			Output::instance()->resultCode(code_website_not_exist);
			return NULL;
		}
		$material = (object)$material;
		return $material;
	}
	
	private static function getMaterialObj($id) {
		$material = self::getMaterial($id);
		if (strcmp($material->module, 'webSite') != 0) {
			Output::instance()->resultCode(code_custom_error, '该主页不存在');
			return NULL;
		}
		$materialObj = simplexml_load_string($material->xml,
				'SimpleXMLElement', LIBXML_NOCDATA);
		return $materialObj;
	}
	
	private static function getNav($materialObjNav, $cid, $userName, $id) {
		$navTop = array();
		$navTopXml = $materialObjNav->NavTop;
		if ($navTopXml->item) {
			foreach ($navTopXml->item as $item) {
				$arrItem = array();
				$arrItem['title'] = $item->title;
				if (strstr($item->url, C('SERVER_HOST'))) {
					$arrItem['url'] = webSite::getTpl(get_session_url($item->url, $cid, $userName), $id);
				} else {
					$arrItem['url'] = $item->url;
				}
				$arrItem['picurl'] = $item->picurl;
				array_push($navTop, $arrItem);
			}
		}
			
		$navBot = array();
		$navBotXml = $materialObjNav->NavBottom;
		if ($navBotXml->item) {
			foreach ($navBotXml->item as $item) {
				$arrItem = array();
				$arrItem['title'] = $item->title;
				if (strstr($item->url, C('SERVER_HOST'))) {
					$arrItem['url'] = webSite::getTpl(get_session_url($item->url, $cid, $userName), $id);
				} else {
					$arrItem['url'] = $item->url;
				}
				$arrItem['picurl'] = $item->picurl;
				array_push($navBot, $arrItem);
			}
		}
			
		$headerId = (int)$materialObjNav->navtoptemplateid;
		if ($headerId != 0) {
			$arr['headerTpl'] = WEBSITE_TEMPLATE. 'header_' . $headerId . '.html';
		}
		$footerId = (int)$materialObjNav->navbottomtemplateid;
		if ($footerId != 0) {
			$arr['footerTpl'] = WEBSITE_TEMPLATE. 'footer_' . $footerId . '.html';
		}
			
		$arr['header'] = $navTop;
		$arr['footer'] = $navBot;
		return $arr;
	}
	
	private static function getTpl($url, $rootId) {
		$urlParam = strstr($url, 'params');
		if ($urlParam) {
			$arrParam = explode("&", $urlParam);
			$params = $arrParam[0];
			$endCharacter = '';
			if (strstr($params, '%7d')) {
				$endCharacter = '%7d';
			} else if (strstr($params, '%7D')) {
				$endCharacter = '%7D';
			} else if (strstr($params, '}')) {
				$endCharacter = '}';
			}
			if ($endCharacter != '') {
				$parentTpl =  ",%22rootid%22:" . $rootId . $endCharacter;
				$url = str_replace($endCharacter, $parentTpl, $url);
			}
		}
		return $url;
	}
}